package com.hogan.hoganproject.base.view;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.viewpager.widget.ViewPager;

/**
 * Created by chenhu on 2015/6/11.
 * 图片的放大与缩小类
 */
public class ZoomImageView extends AppCompatImageView implements ViewTreeObserver.OnGlobalLayoutListener, ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener {

    private boolean mOnce;
    //初始化缩放的值
    private float mInitScale;
    //双击放大的值
    private float mMidScale;
    //放大的最大值
    private float mMaxScale;
    private Matrix mScaleMatrix;
    //捕获用户多点触控时的值
    private ScaleGestureDetector mScaleGestureDetector;
    /**
     * **************自由移动*****************
     */
    //记录上次多点杀触控的数量
    private int mLastPointerCount;
    private float mLastX;
    private float mLastY;
    private boolean isCanDrag;
    private int mTouchSlop;
    private boolean isCheckLeftAndRight, isCheckTopAndBottom;
    /**
     * **************双击放大缩小功能*****************
     */
    private GestureDetector mGestureDetector;
    private boolean isAutoScale;

    public ZoomImageView(Context context) {
        this(context, null);
    }

    public ZoomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScaleMatrix = new Matrix();
        mScaleGestureDetector = new ScaleGestureDetector(context, this);
        setOnTouchListener(this);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if (isAutoScale) {
                    return true;
                }
                float x = e.getX();
                float y = e.getY();
                if (getScale() < mMidScale) {


                    postDelayed(new AutoScaleRunnable(mMaxScale, x, y), 20);
                    isAutoScale = true;
                } else {


                    postDelayed(new AutoScaleRunnable(mInitScale, x, y), 20);
                    isAutoScale = true;
                }

                return true;
            }
        });
        super.setScaleType(ScaleType.MATRIX);
    }

    /**
     * 自动放大与缩小
     */
    private class AutoScaleRunnable implements Runnable {
        //缩放的目标值
        private float mTargeScale;
        //缩放的中心点
        private float x;
        private float y;
        //放大的倍数，与缩小的倍数
        private final float BIGGER = 1.07f;
        private final float SMALL = 0.94f;
        //临时变量
        private float tmpScale;

        public AutoScaleRunnable(float mTargeScale, float x, float y) {

            this.mTargeScale = mTargeScale;
            this.x = x;
            this.y = y;
            if (getScale() < mTargeScale) {
                tmpScale = BIGGER;
            }
            if (getScale() > mTargeScale) {
                tmpScale = SMALL;
            }
        }

        @Override
        public void run() {
            //进行缩放
            mScaleMatrix.postScale(tmpScale, tmpScale, x, y);
            checkBorderAndCenterWhenScale();
            setImageMatrix(mScaleMatrix);
            float currentScale = getScale();
            if ((tmpScale > 1.0f && currentScale < mTargeScale)
                    || (tmpScale < 1.0f && currentScale > mTargeScale)) {
                postDelayed(this, 20);

            } else {  //设置为我们的目标值
                float scale = mTargeScale / currentScale;
                mScaleMatrix.postScale(scale, scale, x, y);
                checkBorderAndCenterWhenScale();
                setImageMatrix(mScaleMatrix);
                isAutoScale = false;
            }

        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    /**
     * Callback method to be invoked when the global layout state or the visibility of views
     * 获取ImageView加载完成的图片
     */
    @Override
    public void onGlobalLayout() {

        if (!mOnce) {
            //得到控件的宽和高
            int width = getWidth();
            int height = getHeight();
            //得到我们的图片，以及宽和高
            Drawable d = getDrawable();
            if (d == null) {
                return;
            }
            int dw = d.getIntrinsicWidth();
            int dh = d.getIntrinsicHeight();
            float scale = 1.0f;
            /**
             * 如果图片的宽度大于控件的宽度，但是高度小于控件的高度，我们将其缩小
             * */
            if (dw > width && dh < height) {
                scale = width * 1.0f / dw;
            }
            /**
             * 如果图片的宽度小于控件的宽度，但是高度大于控件的高度，我们将其缩小
             * */
            if (dh > height && dw < width) {
                scale = height * 1.0f / dh;
            }
            /**
             * 如果图片的宽度小于控件的宽度，但是高度小于控件的高度，我们将其放大
             * */
            if ((dw > width && dh > height) || (dw < width && dh < height)) {
                scale = Math.min(width * 1.0f / dw, height * 1.0f / dh);
            }
            /**
             * 得到初始化时缩放的比例
             * */
            mInitScale = scale;
            mMaxScale = mInitScale * 4;
            mMidScale = mInitScale * 2;
            //将图片移动至屏幕的中心
            int dx = getWidth() / 2 - dw / 2;
            int dy = getHeight() / 2 - dh / 2;
            mScaleMatrix.postTranslate(dx, dy);
            mScaleMatrix.postScale(mInitScale, mInitScale, width / 2, height / 2);
            setImageMatrix(mScaleMatrix);
            mOnce = true;
        }
    }

    /**
     * 获取当前图片的缩放值
     */
    public float getScale() {
        float[] values = new float[9];
        mScaleMatrix.getValues(values);
        return values[Matrix.MSCALE_X];
    }

    /**
     * 缩放进行中(缩放区间mMidScale，mMaxScale)
     *
     * @param detector
     */
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float scale = getScale();
        float scaleFactor = detector.getScaleFactor();

        if (getDrawable() == null) {
            return true;
        }
        //缩放范围控制
        if ((scale < mMaxScale && scaleFactor > 1.0f)
                || (scale > mInitScale && scaleFactor < 1.0f)) {
            if (scale * scaleFactor < mInitScale) {
                scaleFactor = mInitScale / scale;
            }

            if (scale * scaleFactor > mMaxScale) {
                scale = mMaxScale / scale;
            }
            //缩放
            mScaleMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());

            checkBorderAndCenterWhenScale();

            setImageMatrix(mScaleMatrix);
        }

        return true;
    }

    /**
     * 获得图片放大缩小以后的宽和高
     */
    private RectF getMatrixRectF() {
        Matrix matrix = mScaleMatrix;
        RectF rectF = new RectF();
        Drawable d = getDrawable();
        if (d != null) {
            rectF.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            matrix.mapRect(rectF);
        }

        return rectF;
    }


    /**
     * 在缩放时进行边界控件以及位置的控制
     */
    private void checkBorderAndCenterWhenScale() {
        RectF rect = getMatrixRectF();
        float deItaX = 0;
        float deItaY = 0;
        int width = getWidth();
        int height = getHeight();
        if (rect.width() >= width) {
            if (rect.left > 0) {
                deItaX = -rect.left;
            }
            if (rect.right < width) {
                deItaX = width - rect.right;
            }
        }
        //边界时防止出现白边，进行检测
        if (rect.height() >= height) {
            if (rect.top > 0) {
                deItaY = -rect.top;
            }
            if (rect.bottom < height) {
                deItaY = height - rect.bottom;
            }
        }
        //宽或高小于控件的宽高 ，让它居中
        if (rect.width() < width) {
            deItaX = width / 2 - rect.right + rect.width() / 2;
        }
        if (rect.height() < height) {
            deItaY = height / 2 - rect.bottom + rect.height() / 2;
        }
        //设置缩放平移
        mScaleMatrix.postTranslate(deItaX, deItaY);

    }

    /**
     * 缩放开始
     *
     * @param detector
     */
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }

    /**
     * 缩放结束
     *
     * @param detector
     */
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {

    }

    /**
     * @param v
     * @param event
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        }
        mScaleGestureDetector.onTouchEvent(event);

        float x = 0;
        float y = 0;
        int pointerCouunt = event.getPointerCount();
        for (int i = 0; i < pointerCouunt; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= pointerCouunt;
        y /= pointerCouunt;
        if (mLastPointerCount != pointerCouunt) {
            isCanDrag = false;
            mLastX = x;
            mLastY = y;
        }
        mLastPointerCount = pointerCouunt;
        RectF rectF = getMatrixRectF();
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                /**
                 * 处理与ViewPager的冲突事件，当图上不是全显示时，不进行ViewPager事件
                 * */
                if (rectF.width() > getWidth() + 0.01 || rectF.height() > getHeight() + 0.01) {
                    if (getParent() instanceof ViewPager) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (rectF.width() > getWidth() + 0.01 || rectF.height() > getHeight() + 0.01) {
                    if (getParent() instanceof ViewPager) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                }
                float dx = x - mLastX;
                float dy = y - mLastY;
                if (!isCanDrag) {
                    isCanDrag = isMoveAction(dx, dy);
                }
                if (isCanDrag) {

                    if (getDrawable() != null) {
                        isCheckLeftAndRight = isCheckTopAndBottom = true;
                        if (rectF.width() < getWidth()) {
                            isCheckLeftAndRight = false;
                            dx = 0;
                        }
                        if (rectF.height() < getHeight()) {
                            isCheckTopAndBottom = false;
                            dy = 0;
                        }

                        mScaleMatrix.postTranslate(dx, dy);
                        checkBorderAndCenterWhenTranslate();
                        setImageMatrix(mScaleMatrix);
                    }

                }
                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mLastPointerCount = 0;
                break;

        }
        return true;
    }

    /**
     * 当移动时，进行边界检查
     */
    private void checkBorderAndCenterWhenTranslate() {
        RectF rectF = getMatrixRectF();
        float deItaX = 0;
        float deItaY = 0;
        int width = getWidth();
        int height = getHeight();
        if (rectF.top > 0 && isCheckTopAndBottom) {
            deItaY = -rectF.top;
        }
        if (rectF.bottom < height && isCheckTopAndBottom) {
            deItaY = height - rectF.bottom;
        }
        if (rectF.left > 0 && isCheckLeftAndRight) {
            deItaX = -rectF.left;
        }
        if (rectF.right < width && isCheckLeftAndRight) {
            deItaX = width - rectF.right;
        }
        mScaleMatrix.postTranslate(deItaX, deItaY);

    }

    /**
     * 判断是否是move
     */
    private boolean isMoveAction(float dx, float dy) {

        return Math.sqrt(dx * dx + dy * dy) > mTouchSlop;
    }
}
